import { useIntersectionObserver } from '@vueuse/core'
import defaultImage from '@/assets/images/200.png'

const myDirective = {
  install (app) {
    // 自定义指令
    app.directive('imgLazy', {
      mounted (el, binding) {
        el.src = defaultImage
        // el是指令绑定到的dom元素
        // binding.value是:<dom v-imgLazy=" binding.value的值"/>
        // console.log(el, binding, 'imgLazy')
        const { stop } = useIntersectionObserver(el,
          ([{ isIntersecting }], abserveDom) => {
            if (isIntersecting) {
              stop()
              // 给dom元素设置src属性值
              el.src = binding.value
              el.onerror = () => {
                el.src = defaultImage
              }
            }
          },
          { threshold: 0 }
        )
      }
    })
  }
}

export default myDirective
